var DBFactory = require('../db/mysql_db');
var async = require('async');
var signDao = module.exports;


//获取签到活动的信息
function getScoreActivity(data, activity, connection, callback) {
    var sql = 'select id, low_s, high_s, score from score_activity where app_sid = ? and activity = ? and status > 0 ';
    connection.query(sql, [data.app_sid, activity], function(err, result) {
        var info = {};
        info.low_s = (result && result[0] && result[0].low_s) ? result[0].low_s : 0;
        info.high_s = (result && result[0] && result[0].high_s) ? result[0].high_s : 0;
        info.activity_id = (result && result[0] && result[0].id) ? result[0].id : 0;
        info.score = (result && result[0] && result[0].score) ? result[0].score : 0;
        info.app_sid = data.app_sid;
        info.account = data.account;
        info.uid = data.uid;
        callback(err, info);
    });
}
//获取sign_state信息
function getSignState(info, connection, callback) {
    var sql = 'select * from sign_state where uid = ? and app_sid = ? ';
    connection.query(sql, [info.uid, info.app_sid], function(err, result) {
       info.total_day = (result && result[0] && result[0].total_day) ? result[0].total_day : 0;
       info.last_sign_time = (result && result[0] && result[0].last_sign_time) ? result[0].last_sign_time : new Date();
       callback(err, info);
    });
}
//修改sign_state信息
function updateSignState(info, connection, callback) {
    var sql;
    var data = {};
    data.uid = info.uid;
    data.account = info.account;
    data.app_sid = info.app_sid;
    if(parseInt(info.total_day) == 0 ) {
        sql = 'insert into sign_state set ? ';
        data.total_day = 1;
        data.last_sign_time = info.last_sign_time;
        connection.query(sql, data, function(err, result) {
            if(result.affectedRows > 0) {
                callback(err, info);
            } else {
                callback('签到失败请重试！');
            }
        });
    } else {
        var arr = compareTime(info.last_sign_time, new Date());
        if(arr.err != undefined) {
            callback(arr.err);
        } else {
            sql = 'update sign_state set last_sign_time = now() , ';
            if(arr.isContinuity == true) {
                sql += ' total_day = total_day + 1 ';
            } else {
                sql += ' total_day = 1 ';
            }
            sql += ' where uid = ? and app_sid = ? ';
            connection.query(sql, [info.uid, info.app_sid], function(err, result) {
                if(result.affectedRows > 0 ) {
                    info.isContinuity = arr.isContinuity;
                    callback(null, info);
                } else {
                    callback('签到失败，请重试！');
                }
            });
        }
    }
}
function compareTime(last_time, now) {
    var d1 = new Date(last_time);
    var d2 = new Date(now);
    var arr = {};
    if(d2.getTime() > d1.getTime()) {
        d1 = d1.getFullYear() + '-' + (parseInt(d1.getMonth()) + 1) + '-' + d1.getDate();
        d2 = d2.getFullYear() + '-' + (parseInt(d2.getMonth()) + 1) + '-' + d2.getDate();
        d1 = new Date(d1);
        d2 = new Date(d2);
        if( parseInt(d2.getTime()) - parseInt(d1.getTime()) == 24*60*60*1000 ) {
            arr.isContinuity = true;
        } else if( parseInt(d2.getTime()) - parseInt(d1.getTime()) > 24*60*60*1000 ) {
            arr.isContinuity = false;
        }
    }
    if(d2.getTime() == d1.getTime()) {
        arr.err = '您今天已经签到过了';
    }
    return arr;
}
//查看当前积分
function getScoreInfo(info, connection, callback) {
    var sql = 'select sign_score from user_app_exInfo where uid = ? and app_sid = ? ';
    connection.query(sql, [info.uid, info.app_sid], function(err, result) {
        info.sign_score = (result && result[0] && result[0].sign_score) ? result[0].sign_score : 0;
        callback(err, info);
    });
}
//记录日志
function signLog(info, comment, sign, connection, callback) {
    var sql = 'insert into score_log set ? ';
    var arr = {};
    arr.uid = info.uid;
    arr.original_score = info.sign_score;
    arr.app_sid = info.app_sid;
    arr.comment = comment;
    arr.sign = sign;
    arr.activity_id = info.activity_id;
    if(!info.variable_score) {
        if(info.isContinuity && parseInt(info.total_day) >= 3) {
            arr.variable_score = info.high_s;
        } else {
            if(info.isContinuity) {
                arr.variable_score = parseInt(info.low_s) * (parseInt(info.total_day) + 1 );
            } else {
                arr.variable_score = parseInt(info.low_s);
                console.log(arr.variable_score);
            }
        }
        info.variable_score = arr.variable_score;
    } else {
        arr.variable_score = info.variable_score;
    }
    if(parseInt(info.variable_score) > 0) {
        connection.query(sql, arr, function(err) {
            if(err) {
                console.log(err);
                callback('记录积分日志发生错误！');
            } else  {
                callback(null, info);
            }
        });
    } else {
        callback(null, info);
    }
}
//修改exInfoScore
function updateSignScore(info, str, connection, callback) {
    var sql ;
    if(str == '+') {
        if(info.first_sign == true) {
            sql = 'update user_app_exInfo set sign_score = sign_score + ?, first_sign = 1 where uid = ? and app_sid = ? ';
        } else {
            sql = 'update user_app_exInfo set sign_score = sign_score + ? where uid = ? and app_sid = ? ';
        }
    } else if(str == '-') {
        sql = 'update user_app_exInfo set sign_score = sign_score - ? where uid = ? and app_sid = ? ';
    }
    if(parseInt(info.variable_score) > 0) {
        connection.query(sql, [info.variable_score, info.uid, info.app_sid], function(err) {
            callback(err, true, info);
        });
    } else {
        callback(null, true, info);
    }
}
//查看是否能领取新人积分礼包
function canReceive(info, connection, callback) {
    var sql = 'select sign_score, first_sign from user_app_exInfo where uid = ? and app_sid = ? ';
    connection.query(sql, [info.uid, info.app_sid], function(err, result) {
        info.sign_score = (result && result[0] && result[0].sign_score) ? result[0].sign_score : 0;
        info.first_sign = (result && result[0] && result[0].first_sign) ? result[0].first_sign : 0;
        if(parseInt(info.first_sign) > 0) {
            callback('您已经领取过该积分礼包了');
        } else {
            info.first_sign = true;
            callback(err, info);
        }
    });
}

signDao.signIn = function(data, cb) {
    if(!data) return cb(new Error(500));
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    connection.beginTransaction(function(err) {
                        callback(err);
                    });
                },

                //获取签到活动的信息
                function (callback) {
                    getScoreActivity(data, '签到', connection, callback);
                },

                //获取sign_state信息
                function (info, callback) {
                    getSignState(info, connection, callback);
                },

                //修改sign_state信息
                function (info, callback) {
                    updateSignState(info, connection, callback);
                },

                //查看当前积分
                function (info, callback) {
                    getScoreInfo(info, connection, callback);
                },

                //记录log
                function (info, callback) {
                    signLog(info, '签到得积分', 0, connection, callback);
                },

                //修改exInfo积分
                function (info, callback) {
                    updateSignScore(info, '+', connection, callback);
                }
            ],function(DbErr,  isSuccess, info) {
                if(DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if(!isSuccess) {
                    connection.rollback( function() {
                        connection.release();
                        cb(info);
                    });
                } else {
                    connection.commit(function (e) {
                        if(e) {
                            connection.rollback( function() {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, info);

                        }
                    });
                }
            });
        }
    });
}

signDao.receiveScore = function(data, cb) {
    if(!data) return cb(new Error(500));
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    connection.beginTransaction(function(err) {
                        callback(err);
                    });
                },

                //查看新用户积分奖励信息
                function (callback) {
                    getScoreActivity(data, '新用户积分奖励', connection, callback);
                },

                //查看是否能领取新人积分礼包
                function (info, callback) {
                    canReceive(info, connection, callback);
                },

                //记录日志
                function (info, callback) {
                    info.variable_score = info.score;
                    signLog(info, '新用户积分奖励', 0, connection, callback)
                },

                //修改exInfo信息
                function (info, callback) {
                    updateSignScore(info, '+', connection, callback)
                }
            ],function(DbErr,  isSuccess, insertId) {
                if(DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if(!isSuccess) {
                    connection.rollback( function() {
                        connection.release();
                        cb(insertId);
                    });
                } else {
                    connection.commit(function (e) {
                        if(e) {
                            connection.rollback( function() {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, insertId);

                        }
                    });
                }
            });
        }
    });
}


function getLogSql(data) {
    var sqls = {};
    sqls.sqlTotal = ' select count(*) as count from score_log where uid = ? and app_sid = ? ';
    sqls.sqlData = ' select * from score_log where uid = ? and app_sid = ? ';
    sqls.totalData = [];
    sqls.data = [];
    sqls.totalData.push(data.uid);
    sqls.totalData.push(data.app_sid);
    sqls.data.push(data.uid);
    sqls.data.push(data.app_sid);
    if(data.activity_id) {
        sqls.sqlTotal += ' and activity_id = ? ';
        sqls.sqlData += ' and activity_id = ? ';
        sqls.totalData.push(data.activity_id);
        sqls.data.push(data.activity_id);
    }
    sqls.sqlData += ' limit ? , ?';
    sqls.data.push(data.start);
    sqls.data.push(data.size);
    return sqls;
}
signDao.logList = function(data, cb) {
    if(!data) return cb(new Error(500));
    var sqls = getLogSql(data);
    DBFactory.poolQuery(sqls.sqlTotal, sqls.totalData,
        function () {
            cb('no collection');
        },
        function (err, total) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            DBFactory.poolQuery(sqls.sqlData, sqls.data,
                function () {
                    cb('no collection');
                },
                function (err, result) {
                    if (err) {
                        console.log(err);
                        cb(err);
                        return;
                    }
                    var list = {};
                    list.data = result;
                    list.total = total[0].count;
                    cb(null, list);
                }
            );
        }
    );
}


function isContinuity(last_time, now) {
    var d1 = new Date(last_time);
    var d2 = new Date(now);
    var arr = {};
    if(d2.getTime() > d1.getTime()) {
        d1 = d1.getFullYear() + '-' + (parseInt(d1.getMonth()) + 1) + '-' + d1.getDate();
        d2 = d2.getFullYear() + '-' + (parseInt(d2.getMonth()) + 1) + '-' + d2.getDate();
        d1 = new Date(d1);
        d2 = new Date(d2);
        if( parseInt(d2.getTime()) - parseInt(d1.getTime()) <= 24*60*60*1000 ) {
            arr.isContinuity = true;
        } else if( parseInt(d2.getTime()) - parseInt(d1.getTime()) > 24*60*60*1000 ) {
            arr.isContinuity = false;
        }
        if(parseInt(d2.getTime()) - parseInt(d1.getTime()) != 0) {
            arr.canSign = true;
        } else {
            arr.canSign = false;
        }
    } else {
        arr.isContinuity = false;
    }
    console.log(arr);
    return arr;
}
signDao.getSignInfo = function(data, cb) {
    if(!data) return cb(new Error(500));
    var sql = 'select user_app_exInfo.sign_score, sign_state.total_day, sign_state.last_sign_time ' +
        ' from user_app_exInfo left join sign_state on user_app_exInfo.uid = sign_state.uid and  user_app_exInfo.app_sid = ? ' +
        ' and sign_state.app_sid = ? where user_app_exInfo.uid = ? ';
    DBFactory.poolQuery(sql, [data.app_sid, data.app_sid, data.uid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            if(result.length > 0 ) {
                var info = {};
                if(result[0] && result[0].last_sign_time) {
                    var arr = isContinuity(result[0].last_sign_time, new Date());
                    info.total_day = (result && result[0] && result[0].total_day && arr.isContinuity) ? result[0].total_day : 0;
                    info.isContinuity = arr.isContinuity;
                    info.canSign = arr.canSign;
                } else {
                    info.isContinuity = false;
                    info.total_day = 0;
                    info.canSign = true;
                }
                info.sign_score = (result && result[0] && result[0].sign_score) ? result[0].sign_score : 0;
                cb(null, info)
            } else {
                cb('获取签到信息失败！');
            }
        }
    );
}

signDao.canReceive = function(data, cb) {
    if(!data) return cb(new Error(500));
    var sql = 'select sign_score, first_sign from user_app_exInfo where uid = ? and app_sid = ? ';
    DBFactory.poolQuery(sql, [data.uid, data.app_sid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var canReceive = (result && result[0] && result[0].first_sign) ? result[0].first_sign : 0;
            if(parseInt(canReceive) > 0) {
                cb(null, false);
            } else {
                cb(null, true);
            }
        }
    );
}